package day240908;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

@WebServlet(urlPatterns={"/language", "/lang", "/lan"})
public class MyLanguageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String header = req.getParameter("lang");
        if (header == null) {
            header = req.getHeader("Accept-Language");
        }
        String responseTest = "Hello World!";
        if (header.startsWith("zh")) {
            resp.setContentType("text/html;charset=UTF-8");
            responseTest = "肚子饿了！";
        }
        resp.getWriter().write(responseTest);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Locale locale = req.getLocale();
        String language = locale.getLanguage();

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        if (language.equals("zh")) {
            out.println("<h1>肚子饿了</h1>");
        } else if (language.equals("en")) {
            out.println("<h1>Hello World!</h1>");
        }
    }
}